<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>领料申请单</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<link rel="stylesheet" href="${pageContext.request.contextPath }/assets/css/layui.css"  media="all">
	<link rel="stylesheet" href="${pageContext.request.contextPath }/assets/css/toastr.min.css"  media="all">
	<link rel="stylesheet" href="${pageContext.request.contextPath }/assets/ztree/css/demo.css" type="text/css">
	<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath }/assets/ztree/css/zTreeStyle/zTreeStyle.css">
	<style type="text/css">
		div, th, td{
			vertical-align:middle;
		}
	</style>
</head>
<body>
<div class="demoTable" style="padding:10px 0 0 15px">
    <div class="layui-inline">
        <input class="layui-input" name="keyword" id="keyword" autocomplete="off" placeholder="请输入单据号">
    </div>
    <button class="layui-btn layui-btn-blue" style="margin: 0 0 0 10px" data-type="reload"><i class="layui-icon layui-icon-search">  搜索</i></button>
</div>
<table class="layui-hide" id="test" lay-filter="test"></table>
<table class="layui-hide" id="testDetial" lay-filter="testDetial"></table>
<div id="productionOrderList" hidden="">
	<br>
	<div class="layui-form-item" style="text-align: center;">
		<div class="layui-inline">
			<label class="layui-form-label">排产单日期</label>
			<div class="layui-input-inline">
				<input lay-verify="productionOrderDate" onclick="editValue()" class="layui-input" type="text" id="productionOrderDate" name="productionOrderDate">
			</div>
		</div>
	</div>
	<button class="layui-btn layui-btn-blue" id="generate" style="margin-left: 40%">生成领料单</button>&emsp;&emsp;&emsp;&emsp;<button type="reset" class="layui-btn layui-btn-primary">重置</button>
	<div style="margin-top: 1em;" id="pickApplyForm">
	</div>
</div>

<div id="formDiv2" hidden>
	<form class="layui-form" id="formID">
		<input id="pickIDs" name="pickIDs" type="hidden">
		<label class="layui-form-label">权限</label>
		<div class="layui-input-inline" style="width:300px;margin-bottom: 15px;">
			<ul class="ztree" id="ztree"></ul>
		</div><br>
		<button class="layui-btn layui-btn-blue" lay-submit lay-filter="subform" style="margin-left:140px">提交</button>
		&emsp;&emsp;&emsp;&emsp;<button type="button" id="clear" class="layui-btn layui-btn-primary">重置</button>
	</form>
</div>

<div id="formDiv3" hidden>
	<form class="layui-form" id="delForm">
		<input id="pickID" name="pickID" type="hidden"><br>
		<label class="layui-form-label">备注</label>
		<div class="layui-textarea-inline">
			<textarea lay-verify="remark" class="layui-textarea" id="remark" name="remark" style="width: 60%;"></textarea>
		</div><br>
		<button class="layui-btn layui-btn-blue" lay-submit lay-filter="delForm" style="margin-left:35%">撤销</button>
		&emsp;&emsp;&emsp;&emsp;<button type="reset" class="layui-btn layui-btn-primary">重置</button>
	</form>
</div>

<script type="text/html" id="toolbarDemo">
	<div class="layui-btn-container">
		<button class="layui-btn layui-btn-blue" lay-event="add"><i class="layui-icon layui-icon-add-1">  新增</i></button>
		<button class="layui-btn layui-btn-blue" lay-event="approval"><i class="layui-icon layui-icon-release">  发起审批</i></button>
	</div>
</script>
 
<script type="text/html" id="barDemo">
	<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">撤销审批</a>
</script>
              
          
<script src="${pageContext.request.contextPath }/assets/layui.js" charset="utf-8"></script>
<script src="${pageContext.request.contextPath }/assets/layui.all.js"></script>
<script src="${pageContext.request.contextPath }/assets/js/jquery.min.js" charset="utf-8"></script>
<script src="${pageContext.request.contextPath }/assets/js/toastr.min.js" charset="utf-8"></script>
<!-- ztree的js -->
<script type="text/javascript" src="${pageContext.request.contextPath }/assets/ztree/js/jquery.ztree.core.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/assets/ztree/js/jquery.ztree.excheck.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/assets/ztree/js/jquery.ztree.exedit.js"></script>
<jsp:include page="ScriptInc.jsp"></jsp:include>
 
<script>

var status = 0;

layui.use(['table','layer','upload','form','laydate'], function(){
	var laydate = layui.laydate;
	  
	//执行一个laydate实例
	laydate.render({
		elem: '#pickDate' //指定元素
	});
	//执行一个laydate实例
	laydate.render({
		elem: '#demandDate' //指定元素
	});
	//执行一个laydate实例
	laydate.render({
		elem: '#productionOrderDate' //指定元素
	});
	
	var table = layui.table;
	var layer = layui.layer,
    form = layui.form;
	
	var $ = layui.jquery, active = {
			reload:function () {
				var keyword = $("#keyword").val();
				console.log(keyword)
				table.reload('contenttable',{
					method:'get',
					where:{pickNum: keyword}
				});
			}
		}
	$('.layui-btn').on('click', function(){
        var type = $(this).data('type');
        active[type] ? active[type].call(this) : '';
    });
	table.render({
	    elem: '#test'
	    ,url:'${pageContext.request.contextPath }/pickApply/listPagePickApply.do'
	    ,toolbar: '#toolbarDemo'
	    ,title: '领料申请单数据表'
	    ,id :'contenttable'
	    ,limits:[10,20,30]
	    ,cols: [[
	      {type: 'checkbox', fixed: 'left'}
	      /* ,{type: 'numbers', title:'序号', width:'5%', unresize: true, sort: true} */
	      ,{field:'pickNum', title:'单据号'}
	      ,{field:'pickDate', title:'日期', templet: function(d){
	          return timestampToDate(d.pickDate.time);
	      }}
	      ,{field:'pickDeptName', title:'部门'}
	      ,{field:'demandDate', title:'排产单日期', templet: function(d){
	          return timestampToDate(d.demandDate.time);
	      }}
	      /* ,{field:'generateOrderID', title:'生产订单号ID', templet: function(d){
	    	  if (d.generateOrderID == '0') {
	    		  return '';
			} else {
				return d.generateOrderID;
			}
	      }} */
	      ,{field:'pickPersonName', title:'制单人'}
	      ,{field:'reserve1', title:'审批状态', templet: function(d){
	    	  if (d.reserve1 == '0') {
	    		  return '未审批';
			}
	    	  if (d.reserve1 == '1') {
	    		  return '审批中';
			}
	    	  if (d.reserve1 == '2') {
	    		  return '已撤销';
			}
	    	  if (d.reserve1 == '3') {
	    		  return '审批通过';
			}
	    	  if (d.reserve1 == '4') {
					return '审批未通过';
			}
	      }}
	      ,{field:'approvalDate', title:'审批日期', templet: function(d){
	    	  if (d.reserve1 == '3' || d.reserve1 == '4') {
	    		  return timestampToDate(d.approvalDate.time);
			} else {
		          return '';
			}
	      }}
	      ,{field:'applicantName', title:'审批人', templet: function(d){
	    	  if (d.reserve1 == '3' || d.reserve1 == '4') {
	    		  return d.applicantName;
			} else {
		          return '';
			}
	      }}
	      ,{field:'approvalRecord', title:'审批记录', templet: function(d){
	    	  return "<a href='javascript:void(0)' style='color:#4D61B3' onclick='attachDeviceEvent(\""+d.pickID+"\")'>"+'查看详细'+"</a>";
	      }}
	      ,{fixed: 'right', title:'操作', toolbar: '#barDemo'}
	    ]]
	    ,page: true
	});
	
	//监听行单击事件
	table.on('row(test)', function(obj){
	  table.render({
		    elem: '#testDetial'
		    ,url:'${pageContext.request.contextPath }/pickApply/listPagePickApplyDetail.do'
		    ,where:{pickID: obj.data.pickID}
		    ,title: '领料申请单详情数据表'
		    ,id :'contentDetialTable'
		    ,limits:[10,20,30]
		    ,cols: [[
		      {type: 'numbers', fixed: 'left', title:'序号'}
		      ,{field:'stockNum', title:'配件编号'}
		      ,{field:'stockName', title:'配件名称'}
		      ,{field:'stockModel', title:'规格型号'}
		      ,{field:'reserve1', title:'计量单位'}
		      ,{field:'reserve2', title:'包装规格'}
		      ,{field:'reserve3', title:'批次号'}
		      ,{field:'quantity', title:'数量'}
		    ]]
		    ,page: true
		});
	});
  
	//头工具栏事件
	table.on('toolbar(test)', function(obj){
		var checkStatus = table.checkStatus(obj.config.id);
	    switch(obj.event){
		    case 'add':
	    		layer.open({
					  type: 1 		//Page层类型
					  ,area: ['70%', '85%'] //宽  高
					  ,title: '新增'
					  ,shade: 0.6 	//遮罩透明度
					  ,shadeClose: true //点击遮罩关闭
					  ,maxmin: true //允许全屏最小化
					  ,anim: 1 		//0-6的动画形式，-1不开启
					  ,content: $('#productionOrderList')
					  ,success: function () {
						  $('#productionOrderDate').val('');
						  $('#pickApplyForm').empty();
						  $('#generate').off("click").on('click', function() {
							 if(status == 0){
								 status = 1;
								 $('#pickApplyForm').empty();
								 var productionOrderDate = $('#productionOrderDate').val();
								 if (productionOrderDate == '') {
									  toastr.warning("请选择排产单日期！");
						        		return false;
								 }
							     $.ajax({
				    		    	type:'post',
				    		    	url:'${pageContext.request.contextPath }/pickApply/generatePickApply.do',
				    		    	data:{"remark1": productionOrderDate},
				    		    	success:function(data){
				    		    		if (data == 0) {
				    		    			toastr.warning("排产单不存在！");
							        		return false;
										} else {
											var pickApply = eval("("+data+")");
											var list = pickApply[0].pickApplyDetailList;
											if (list.length == 0) {
												$('#pickApplyForm').append('<div style="text-align: center;padding-top: 8em;font-size: 20px;">'+
														'线边库充足，可以开始生产</div><button class="layui-btn layui-btn-blue" id="close" '+
														'style="margin: 1em 0 0 45%;">开始生产</button>');
												$('#close').off("click").on('click', function() {
													layer.close(1);
												})
											} else {
												var tbody = '';
												for (var i = 0; i < list.length; i++) {
													tbody = tbody + '<tr><td><input readonly class="layui-input" type="text" name="stockNum" value="'+list[i].stockNum+'"></td>'+
														'<td><input readonly class="layui-input" type="text" name="stockName" value="'+list[i].stockName+'"></td>'+
														'<td><input readonly class="layui-input" type="text" name="stockModel" value="'+list[i].stockModel+'"></td>'+
														'<td><input readonly class="layui-input" type="text" name="paunit" value="'+list[i].reserve1+'"></td>'+
														'<td><input readonly class="layui-input" type="text" name="packNorm" value="'+list[i].reserve2+'"></td>'+
														'<td><input lay-verify="batch" class="layui-input" type="text" name="batch" value="'+list[i].reserve3+'"></td>'+
														'<td><input lay-verify="reserve5" class="layui-input" type="text" value="'+list[i].reserve5+'"></td>'+
														'<td><input lay-verify="quantity" class="layui-input" type="number" oninput="vQuantity(this.value,'+i+','+list[i].reserve4+')" name="quantity" id="quantity'+i+'" value="'+list[i].quantity+'"></td></tr>';
												}
												if (pickApply[0].reserve5 == '2') {
													$('#pickApplyForm').append('<form class="layui-form" id="addform"><h1 style="text-align: center;margin-bottom: 15px;">缓存区叫料单</h1>'+
															'<input class="layui-input" type="hidden" name="reserve5" value="'+pickApply[0].reserve5+'">'+
															'<input class="layui-input" type="hidden" name="generateOrderID" value="'+pickApply[0].generateOrderID+'">'+
															'<input class="layui-input" type="hidden" name="pickDate" value="'+timestampToDate(pickApply[0].pickDate.time)+'">'+
															'<div class="layui-form-item" style="text-align: center;"><div class="layui-inline"><label class="layui-form-label">'+
															'需求日期</label><div class="layui-input-inline"><input lay-verify="productionOrderDate" class="layui-input" '+
															'type="text" readonly id="demandDate" name="demandDate" value="'+timestampToDate(pickApply[0].demandDate.time)+'">'+
															'</div></div></div><table class="layui-table" lay-filter="formTable" style="width:95%;text-align: center;'+
															'margin: 1em 1em 0 1em;"><thead><tr><td>配件编号</td><td>配件名称</td><td>规格型号</td><td>计量单位</td>'+
															'<td>包装规格</td><td>批号</td><td>所需总数量</td><td>所需领料数量</td></tr></thead><tbody>'+tbody+'</tbody></table><button '+
															'class="layui-btn layui-btn-blue" lay-submit lay-filter="addform" style="margin: 1em 0 1em 47%;">叫料</button></form>');
												} else {
													$('#pickApplyForm').append('<form class="layui-form" id="addform"><h1 style="text-align: center;margin-bottom: 15px;">领料申请单</h1>'+
															'<input class="layui-input" type="hidden" name="reserve5" value="'+pickApply[0].reserve5+'">'+
															'<input class="layui-input" type="hidden" name="generateOrderID" value="'+pickApply[0].generateOrderID+'">'+
															'<input class="layui-input" type="hidden" name="pickDate" value="'+timestampToDate(pickApply[0].pickDate.time)+'">'+
															'<div class="layui-form-item" style="text-align: center;"><div class="layui-inline"><label class="layui-form-label">'+
															'需求日期</label><div class="layui-input-inline"><input lay-verify="productionOrderDate" class="layui-input" '+
															'type="text" readonly id="demandDate" name="demandDate" value="'+timestampToDate(pickApply[0].demandDate.time)+'">'+
															'</div></div></div><div class="layui-form-item" style="text-align: center;"><div class="layui-inline"><label class="layui-form-label">订单号1</label><div class="layui-input-inline">'+
															'<input lay-verify="reserve2" class="layui-input" type="text" id="reserve2" name="reserve2" value="'+pickApply[0].reserve2+'">'+
															'</div><span style="color:red; font-size: 24px;float: left;margin: 12px 0 0 0;">*</span></div><div class="layui-inline">'+
															'<label class="layui-form-label">数量1</label><div class="layui-input-inline"><input lay-verify="reserve3" class="layui-input" '+
															'type="number" id="reserve3" name="reserve3" value="'+pickApply[0].reserve3+'"></div><span style="color:red; font-size: 24px;float: left;margin: 12px 0 0 0;">*</span>'+
															'</div></div><div class="layui-form-item" style="text-align: center;"><div class="layui-inline"><label class="layui-form-label">订单号2</label><div class="layui-input-inline">'+
															'<input lay-verify="orderSN" class="layui-input" type="text" id="orderSN" name="orderSN"></div><span style="color:red; font-size: 24px;float: left;margin: 12px 0 0 0;">&nbsp;&nbsp;</span></div><div class="layui-inline">'+
															'<label class="layui-form-label">数量2</label><div class="layui-input-inline"><input class="layui-input" '+
															'type="number" id="orderNum" name="orderNum"></div></div><table class="layui-table" lay-filter="formTable" style="width:95%;text-align: center;'+
															'margin: 1em 1em 0 1em;"><thead><tr><td>配件编号</td><td>配件名称</td><td>规格型号</td><td>计量单位</td>'+
															'<td>包装规格</td><td>批号</td><td>所需总数量</td><td>所需领料数量</td></tr></thead><tbody>'+tbody+'</tbody></table><button '+
															'class="layui-btn layui-btn-blue" lay-submit lay-filter="addform" style="margin: 1em 0 1em 1em;">领料</button></form>');
												}
											}
										}
				    		    	}
				    		    		
				    		    })
							 }
						  })
					  }
					  ,end: function () {
						  var formDiv = document.getElementById('productionOrderList');
						  formDiv.style.display = '';
					  }
					});
	      	break;
	      	
	    	case 'approval':
	        	var data = checkStatus.data;
	        	var idArr = new Array();
	        	if(data.length==0){
	        		toastr.warning("请至少选择一条记录！");
	        		return false;
	        	}
	        	var pickIDs = '';
	        	for(var i=0;i<data.length;i++){
	        		if (data[i].reserve1 != '0' && data[i].reserve1 != '2' && data[i].reserve1 != '4') {
	        			toastr.warning("不能重复提交审批！");
		        		return false;
					}
	        		if (i == 0) {
	        			pickIDs = pickIDs + data[i].pickID;
					} else {
						pickIDs = pickIDs + ',' + data[i].pickID;
					}
	        	}
	        	console.log(pickIDs)
	        	$("#pickIDs").val(pickIDs);
				layer.open({
					type: 1 		//Page层类型
					,area: ['30%', '70%'] //宽  高
					,title: '选择审批人'
					,shade: 0.6 	//遮罩透明度
					,maxmin: true //允许全屏最小化
					,anim: 1 		//0-6的动画形式，-1不开启
					,content:$("#formDiv2") 
					,success: function(data){
						successOther(laydate,data);
						form.render();
					}
					,end: function () {
						var formDiv = document.getElementById('formDiv2');
						formDiv.style.display = '';
					}
				});
	      	break;
	      	case 'select':
	      		console.log(obj)
	      	break;
	      		
	    	case 'delete':
	        	var data = checkStatus.data;
	        	var idArr = new Array();
	        	if(data.length==0){
	        		toastr.warning("请至少选择一条记录！");
	        		return false;
	        	}
	        	var pickIDs = '';
	        	for(var i=0;i<data.length;i++){
	        		if(data[i].reserve1!= '0' || data[i].reserve1!= '1' || data[i].reserve1!= '2'){
		        		toastr.warning("只能选择未审核的记录！");
		        		return false;
		        	}
	        		if (i == 0) {
	        			pickIDs = pickIDs + data[i].pickID;
					} else {
						pickIDs = pickIDs + ',' + data[i].pickID;
					}
	        	}
	        	console.log(pickIDs)
	        	layer.confirm('确定删除吗？', function(index){
	    		    $.ajax({
	    		    	type:'post',
	    		    	url:'${pageContext.request.contextPath }/pickApply/deletePickApply.do',
	    		    	data:{"pickIDs": pickIDs},
	    		    	success:function(data){
	    		    		if(data>0){
	    		    			toastr.success("删除成功！");
	    		    			setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
	    							//关闭模态框
	    							// 父页面刷新
	    							window.location.reload();  
	    						},2000);
	    		    		}else{
	    		    			toastr.warning("删除失败！");
	    		    		}
	    		    	}
	    		    		
	    		    })
	    		    layer.close(index);
	    		  });
	      	break;
	      	case 'select':
	      		console.log(obj)
	      	break;
	    };
	});
  
	//监听行工具事件
	table.on('tool(test)', function(obj){
		var data = obj.data;
		console.log(obj)
		if(obj.event === 'del'){
			if (obj.data.reserve1 != '0' && obj.data.reserve1 != '1' && obj.data.reserve1 != '2') {
				toastr.warning("该记录不能撤销审批！");
        		return false;
			}
			layer.open({
				  type: 1 		//Page层类型
				  ,area: ['40%', '50%'] //宽  高
				  ,title: '撤销审批'
				  ,shade: 0.6 	//遮罩透明度
				  ,shadeClose: true //点击遮罩关闭
				  ,maxmin: true //允许全屏最小化
				  ,anim: 1 		//0-6的动画形式，-1不开启
				  ,content: $('#formDiv3')
				  ,success: function () {
					  document.getElementById("delForm").reset();
					  $('#pickID').val(obj.data.pickID);
				  }
				,end: function () {
					  var formDiv = document.getElementById('formDiv3');
					  formDiv.style.display = '';
				  }
			})
		} else if(obj.event === 'edit'){
			if (obj.data.reserve1 != '0') {
				toastr.warning("只能修改未审核的记录！");
				return false;
			}
			layer.open({
				  type: 1 		//Page层类型
				  ,area: ['50%', '70%'] //宽  高
				  ,title: '修改编辑'
				  ,shade: 0.6 	//遮罩透明度
				  ,maxmin: true //允许全屏最小化
				  ,anim: 1 		//0-6的动画形式，-1不开启
				  ,content: $('#formDiv')
				  ,success: function () {
					//回显表单数据
					for(var i=0;i<Object.entries(data).length;i++) {
						var id = '#' + Object.entries(data)[i][0];
						var text = Object.entries(data)[i][1];
						$(id).val(text);
					}
					//保留第一行
				    $("#addTbody  tr:not(:first)").remove();
					$.ajax({
				    	type:'post',
				    	url:'${pageContext.request.contextPath }/pickApply/listAllPickApplyDetail.do',
				    	data:{"pickID": obj.data.pickID},
				    	success:function(data){
				    		var list = eval("("+data+")");
				    		for (var i = 0; i < list.length; i++) {
								if (i == 0) {
									$("input[name='stockNum']").val(list[i].stockNum);
									$("input[name='stockName']").val(list[i].stockName);
									$("input[name='stockModel']").val(list[i].stockModel);
									$("input[name='quantity']").val(list[i].quantity);
								} else {
									var tbody = document.getElementById("addTbody");
									var row = tbody.insertRow();
									var innerHTML1 = '<input lay-verify="stockNum" class="layui-input" type="text" name="stockNum" value="'+list[i].stockNum+'">';
									var innerHTML2 = '<input lay-verify="stockName" class="layui-input" type="text" name="stockName" value="'+list[i].stockName+'">';
									var innerHTML3 = '<input lay-verify="stockModel" class="layui-input" type="text" name="stockModel" value="'+list[i].stockModel+'">';
									var innerHTML4 = '<input lay-verify="quantity" class="layui-input" type="number" name="quantity" value="'+list[i].quantity+'">';
									var innerHTML5 = '<a class="layui-btn layui-btn-primary layui-btn-sm delTr2"><i class="layui-icon"></i>';
									row.insertCell(0).innerHTML = innerHTML1;
									row.insertCell(1).innerHTML = innerHTML2;
									row.insertCell(2).innerHTML = innerHTML3;
									row.insertCell(3).innerHTML = innerHTML4;
									row.insertCell(4).innerHTML = innerHTML5;
									tbody.appendChild(row);
									$('.delTr2').on('click', function() {
										console.log($(this)[0].parentNode.parentNode)
										var tr = $(this)[0].parentNode.parentNode;
										var tbody = tr.parentNode;
										if (tbody.rows.length==1) {
											toastr.warning("至少添加一条数据!");
											return false;
										} else {
											tbody.removeChild(tr);
										}
									});
								}
							}
				    	}
				    		
				    });
					$('#addTr').on('click', function() {
						var tbody = document.getElementById("addTbody");
						var row = tbody.insertRow();
						var innerHTML1 = '<input lay-verify="stockNum" class="layui-input" type="text" name="stockNum">';
						var innerHTML2 = '<input lay-verify="stockName" class="layui-input" type="text" name="stockName">';
						var innerHTML3 = '<input lay-verify="stockModel" class="layui-input" type="text" name="stockModel">';
						var innerHTML4 = '<input lay-verify="quantity" class="layui-input" type="number" name="quantity">';
						var innerHTML5 = '<a class="layui-btn layui-btn-primary layui-btn-sm delTr2"><i class="layui-icon"></i>';
						row.insertCell(0).innerHTML = innerHTML1;
						row.insertCell(1).innerHTML = innerHTML2;
						row.insertCell(2).innerHTML = innerHTML3;
						row.insertCell(3).innerHTML = innerHTML4;
						row.insertCell(4).innerHTML = innerHTML5;
						tbody.appendChild(row);
						$('.delTr2').on('click', function() {
							console.log($(this)[0].parentNode.parentNode)
							var tr = $(this)[0].parentNode.parentNode;
							var tbody = tr.parentNode;
							if (tbody.rows.length==1) {
								toastr.warning("至少添加一条数据!");
								return false;
							} else {
								tbody.removeChild(tr);
							}
						});
					});
					  $('.delTr').on('click', function() {
						console.log($(this)[0].parentNode.parentNode)
						var tr = $(this)[0].parentNode.parentNode;
						var tbody = tr.parentNode;
						if (tbody.rows.length==1) {
							toastr.warning("至少添加一条数据!");
							return false;
						} else {
							tbody.removeChild(tr);
						}
					});
					  form.render();
				  }	
				  ,end: function () {
				  	var formDiv = document.getElementById('formDiv');
				  	formDiv.style.display = '';
			  	  }
			});
		}
	});
	/**
     * 表单校验
     */
    form.verify({
    	//value：表单的值、item：表单的DOM对象
    	/* pickNum: function(value){
    		if(value == ''){
    			return '不能为空';
    		}
    	},
    	pickDate: function(value){
    		if(value == ''){
    			return '不能为空';
    		}
    	},
    	pickDept: function(value){
    		if(value == ''){
    			return '不能为空';
    		}
    	},
    	demandDate: function(value){
    		if(value == ''){
    			return '不能为空';
    		}
    	},
    	generateNum: function(value){
    		if(value == ''){
    			return '不能为空';
    		}
    	},
    	generateOrderID: function(value){
    		if(value == ''){
    			return '不能为空';
    		}
    	},
    	pnum: function(value){
    		if(value == ''){
    			return '不能为空';
    		}
    	},
    	pnorm: function(value){
    		if(value == ''){
    			return '不能为空';
    		}
    	},
    	stockNum: function(value){
    		if(value == ''){
    			return '不能为空';
    		}
    	},
    	stockName: function(value){
    		if(value == ''){
    			return '不能为空';
    		}
    	},
    	stockModel: function(value){
    		if(value == ''){
    			return '不能为空';
    		}
    	},
    	quantity: function(value){
    		if(value == ''){
    			return '不能为空';
    		}
    	}, */
    	reserve2: function(value){
    		if(value == ''){
    			return '订单号不能为空';
    		}
    	},
    	reserve3: function(value){
    		if(value == ''){
    			return '数量不能为空';
    		}
    	},
    	batch: function(value){
    		if(value == ''){
    			return '批次号不能为空';
    		}
    	},
    	reserve5: function(value){
    		if(value == ''){
    			return '所需总数量不能为空';
    		}
    	},
    	quantity: function(value){
    		if(value == ''){
    			return '所需领料数量不能为空';
    		}
    	}
    });
    /**
     * 通用表单提交(AJAX方式)（新增）
     */
    form.on('submit(addform)', function (data) {
    	$.ajax({
			url : '${pageContext.request.contextPath }/pickApply/savePickApply.do',
			data : $('#addform').serialize(),
			type : "post",
			dataType : "json",
			}).done(
				function(res) {
					if (res == -1) {
						toastr.success('叫料成功！');
						setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
							//关闭模态框
							// 父页面刷新
							window.location.reload();  
						},2000);
					}
					if (res > 0) {
						toastr.success('新增成功！');
						setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
							//关闭模态框
							// 父页面刷新
							window.location.reload();  
						},2000);
					}
				}
			).fail(
				function(res) {
					layer.close(1);
					toastr.error('新增失败！');
				}
			)
			return false;
    });
    /**
     * 通用表单提交(AJAX方式)提交审批
     */
	form.on('submit(subform)', function (data) {
		var ztree = getCheck("ztree");
		var pickIDs = $('#pickIDs').val();
		if (!ztree) {
			return false;
		}
		console.log(pickIDs)
		console.log(ztree)
		$.ajax({
			url : '${pageContext.request.contextPath }/pickApply/approvalPickApply.do',
			type : "post",
			data : {"pickIDs":pickIDs, "ztree":ztree},
			async: false,
			dataType : "json",
		}).done(
			function(res) {
				if (res > 0) {
					toastr.success('提交成功');
					setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
						//关闭模态框
						// 父页面刷新
						window.location.reload();  
					},2000);
				}
			}
		).fail(
			function(res) {
				toastr.error('提交失败');
			}
		)
		return false;
	});
    /**
     * 通用表单提交(AJAX方式)撤销
     */
	form.on('submit(delForm)', function (data) {
		$.ajax({
			url : '${pageContext.request.contextPath }/pickApply/cancelPickApply.do',
			type : "post",
			data : $('#delForm').serialize(),
		}).done(
			function(res) {
				if (res > 0) {
					toastr.success('撤销审批成功');
					setTimeout(function(){  //使用  setTimeout（）方法设定定时2000毫秒
						//关闭模态框
						// 父页面刷新
						window.location.reload();  
					},2000);
				}
			}
		).fail(
			function(res) {
				toastr.error('撤销审批失败');
			}
		)
		return false;
	});
});

toastr.options.positionClass = 'toast-top-center'; //提示框的位置设置为中上

function editValue(){
	status = 0;
}


</script>
<script type="text/javascript">
var setting = {
		data:{//表示tree的数据格式
			simpleData:{
				enable:true,//表示使用简单数据模式
				idKey:"id",//设置之后id为在简单数据模式中的父子节点关联的桥梁
				pidKey:"pId",//设置之后pid为在简单数据模式中的父子节点关联的桥梁和id互相对应
				rootId:"null"//pid为null的表示根节点
			}
		},
		view:{//表示tree的显示状态
			selectMulti:false//表示禁止多选
		},
		check:{//表示tree的节点在点击时的相关设置
			enable:true,//是否显示radio/checkbox
			chkStyle:"checkbox",//值为checkbox或者radio表示
			checkboxType:{p:"",s:""},//表示父子节点的联动效果
			radioType:"level"//设置tree的分组
		}, 
		/* callback:{//表示tree的一些事件处理函数
			onClick:handlerClick,
		} */
	}
/* 加载树 */
function successOther(laydate,data){
	ztree(data);
}
function ztree(data){
	//第一步，先获取所有的权限信息，用树结构进行展示
	var treeData = [];
	$.ajax({
		type: "post",
		url: "${pageContext.request.contextPath }/memberMana/listAllUser.do",
		dataType: 'JSON',
		async: false,
		success: function (arr) {
			for(var i=0;i<arr.length;i++){
				var childrens = [];
				var userList = arr[i].userList;
				for(var j=0;j<userList.length;j++){
					childrens.push({id:userList[j].uid,name:userList[j].userName,pId:null});
				}
				treeData.push({id:arr[i].did,name:arr[i].name,pId:null,children:childrens});
			}
			$.fn.zTree.init($("#ztree"),setting,treeData);
		},
		error : function(msg) {
			toastr.warning('树加载异常!');
		}
	});
}
function getCheck(id){
	//在提交表单之前，使用ztree提供的方式获取选中的节点
	var treeObj = $.fn.zTree.getZTreeObj(id);//获得ztree对象
	var nodes = treeObj.getCheckedNodes(true);//在提交表单之前将选中的checkbox收集
	var array = new Array();
	for(var i=0;i<nodes.length;i++){
		if (nodes[i].level == 1) {
			var id = nodes[i].id;
			array.push(id);
		}
	}
	if (array.length > 1) {
		toastr.warning('只能选择一条数据');
		return false;
	}
	var ids = array.join(",");
	return ids;
}
function vQuantity(value,index,count){
	if (count != undefined) {
		var q = parseFloat(value);
		var all = parseFloat(count);
		if (q > all) {
			toastr.warning('数量不能大于缓存区库存数量');
			$('#quantity'+index).val(all);
		}
	}
}

toastr.options.positionClass = 'toast-top-center'; //提示框的位置设置为中上
//审批记录
function attachDeviceEvent(pickID){
    layer.open({
        type: 1 					//Page层类型
        ,area: ['65%', '60%']   //宽  高
        ,title: '审批记录'
        ,shade: 0.6 				//遮罩透明度
        ,maxmin: true 			    //允许全屏最小化
        ,anim: 1 					//0-6的动画形式，-1不开启
        ,content: '<table class="layui-hide" id="lookupTable1" lay-filter="lookupTable1"></table>'
        ,success: function(){
            layui.use(['table'], function(){
                var table = layui.table;
                table.render({
                    elem: '#lookupTable1'
                    ,url: '${pageContext.request.contextPath }/approvalRecord/listAllApprovalRecord.do?pickID='+pickID
                    ,title: '审批记录明细'
                    ,id :'contenttable'
                    ,limits:[10,20,30]
                    ,cols: [[
                        {title:'序号', fixed: 'left', type:'numbers'},
                        {field:'submitDate', title:'操作日期',templet: function(d){
              		          return timestampToDateTime(d.submitDate.time);
              	      }},
                        {field:'approvalType', title:'审批类型'},
                        {field:'submitterName', title:'提交人'},
                        {field:'approverName', title:'审批人'},
                        {field:'status', title:'审批状态',templet: function(d){
            		    	if (d.status == '1') {
								return '提交申请';
							}
            		    	if (d.status == '2') {
								return '撤销申请';
							}
            		    	if (d.status == '3') {
								return '审批通过';
							}
            		    	if (d.status == '4') {
								return '审批未通过';
							}
                	    }},
                        {field:'remark', title:'备注'}
                    ]]
                    ,page: false
                });
            });
        }
    });
}

</script>
</body>
</html>